package dyyx.jackson;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import dyyx.DataUtil;
import dyyx.JacksonUtil;
import dyyx.dto.Department;

public class TestAll {

	public static void main(String[] args) throws Exception {
		
		Department dept = DataUtil.getDepartment();
		System.out.println(dept);

		String json = JacksonUtil.toString(dept, true);
		System.out.println(json);		
		
		// {"id":1,"name":"Department1","users":[{"id":1,"name":"cat"},{"id":2,"name":"tiger"}]}

		// ObjectMapper mapper = JacksonUtil.getObjectMapper();
		ObjectMapper mapper = new ObjectMapper();
		// 数据绑定
		dept = mapper.readValue(json, Department.class);
		System.out.println(dept);
		
		// tree   树模型
        JsonNode rootNode = mapper.readTree(json);
		System.out.println(rootNode);
		JsonNode idNode = rootNode.get("id");
		JsonNode nameNode = rootNode.get("name");
		JsonNode nullNode = rootNode.get("xxx");
        JsonNode nullNodeByPath = rootNode.path("xxx");

		System.out.println("idNode="+idNode);
		System.out.println("nameNode="+nameNode);
		System.out.println("nullNode="+nullNode);
		System.out.println("nullNodeByPath="+nullNodeByPath);
		
		System.out.println("idNode isArray "+idNode.isArray());
		System.out.println("idNode size "+idNode.size());

		
		System.out.println("idNode "+idNode.asInt() +" "+idNode.asText());

		JsonNode usersNode = rootNode.get("users");
		System.out.println("usersNode="+usersNode);
		
		if(usersNode.isArray()) {
			int size = usersNode.size();
			for(int i=0;i<size;i++) {
				JsonNode userNode = usersNode.get(0);
				System.out.println("userNodes["+i+"]="+userNode);
			}
		}
		
		// stream 
		
        JsonFactory factory = new JsonFactory();

        JsonParser parser = factory.createParser(json);
        while (!parser.isClosed()){
            JsonToken token = parser.currentToken();
            System.out.println(token);
            parser.nextToken();
        }

	}
}
